package org.wcms.surrounded.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.wcms.surrounded.Constants;
import org.wcms.surrounded.model.User;
import org.wcms.surrounded.utils.Utils;

import com.google.inject.Singleton;

@Singleton
public class SurroundedLogoutServlet extends HttpServlet {

	private static final long serialVersionUID = 7087949152592827322L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        handle(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        handle(req, resp);
    }
	
    protected void handle(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
		
		HttpSession httpSession = req.getSession();
        User user = (User) httpSession.getAttribute(Constants.SURROUNDED_SESSION_USER);
        
        if (user != null) {
        		
			Cookie logOutCookie = new Cookie(Constants.SURROUNDED_COOKIE, Utils.getGuidFromId(user.getId()));
			logOutCookie.setMaxAge(0);	        
			resp.addCookie(logOutCookie);	        
			
	        httpSession.removeAttribute(Constants.SURROUNDED_SESSION_USER);
        }
        
        resp.sendRedirect("/");
	}	
}
